package com.knowledgegraph.neo4j.repository;

import com.knowledgegraph.neo4j.entity.GraphRelationship;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Neo4j 关系仓库
 */
@Repository
public interface GraphRelationshipRepository extends Neo4jRepository<GraphRelationship, Long> {
    
    /**
     * 根据图谱ID查询关系
     */
    @Query("MATCH (start)-[r]->(end) WHERE r.graphId = $graphId RETURN r, start, end")
    List<GraphRelationship> findByGraphId(@Param("graphId") Long graphId);
    
    /**
     * 根据关系类型查询
     */
    @Query("MATCH (start)-[r]->(end) WHERE r.type = $type RETURN r, start, end")
    List<GraphRelationship> findByType(@Param("type") String type);
    
    /**
     * 根据起始节点ID查询关系
     */
    @Query("MATCH (start)-[r]->(end) WHERE ID(start) = $startNodeId RETURN r, start, end")
    List<GraphRelationship> findByStartNodeId(@Param("startNodeId") Long startNodeId);
    
    /**
     * 根据结束节点ID查询关系
     */
    @Query("MATCH (start)-[r]->(end) WHERE ID(end) = $endNodeId RETURN r, start, end")
    List<GraphRelationship> findByEndNodeId(@Param("endNodeId") Long endNodeId);
    
    /**
     * 查询两个节点之间的关系
     */
    @Query("MATCH (start)-[r]->(end) WHERE ID(start) = $startNodeId AND ID(end) = $endNodeId RETURN r, start, end")
    List<GraphRelationship> findBetweenNodes(@Param("startNodeId") Long startNodeId, @Param("endNodeId") Long endNodeId);
    
    /**
     * 根据图谱ID和状态查询关系
     */
    @Query("MATCH (start)-[r]->(end) WHERE r.graphId = $graphId AND r.status = $status RETURN r, start, end")
    List<GraphRelationship> findByGraphIdAndStatus(@Param("graphId") Long graphId, @Param("status") String status);
    
    /**
     * 删除图谱下的所有关系
     */
    @Query("MATCH (start)-[r]->(end) WHERE r.graphId = $graphId DELETE r")
    void deleteByGraphId(@Param("graphId") Long graphId);
    
    /**
     * 统计图谱下的关系数量
     */
    @Query("MATCH (start)-[r]->(end) WHERE r.graphId = $graphId RETURN count(r)")
    Long countByGraphId(@Param("graphId") Long graphId);
    
    /**
     * 根据强度范围查询关系
     */
    @Query("MATCH (start)-[r]->(end) WHERE r.strength >= $minStrength AND r.strength <= $maxStrength RETURN r, start, end")
    List<GraphRelationship> findByStrengthBetween(@Param("minStrength") Double minStrength, @Param("maxStrength") Double maxStrength);
}